﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using GS.CMS.Entities;
using System.Data;
using GS.Config;

public partial class product_detail : System.Web.UI.Page
{
    Products _Products = new Products();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindData();
        }
        string html = "";
        html += @"<div class='GPH-g1'>
                            <div class='GPphanhoi'>
                                    <div class='googleone'>
                                        <div class='google-1'>
                                            <div class='google-item'>";
                //html += "<g:plusone href='https://profiles.google.com/thanhnienonline2008'></g:plusone>";            
                html += "<g:plusone size='medium'></g:plusone>";            
                                    html +=@"</div>
                                        </div>
                                    </div>
                                    <div class='tweet'>
                                        <a href='http://twitter.com/share' class='twitter-share-button' data-count='horizontal'>
                                        </a>
                                        <script type='text/javascript' src='http://platform.twitter.com/widgets.js'></script>
                                    </div>
                                    <div class='facebook-1'>
                                        <div class='facabook'>";
                                    html += "<iframe src=\"http://www.facebook.com/plugins/like.php?href=" + Page.Request.Url + "&amp;layout=button_count&amp; show_faces=true&amp;width=450&amp;action=like&amp;font=tahoma&amp;colorscheme=light\" scrolling=\"no\" frameborder=\"0\" allowTransparency=\"true\" style=\"border:none; overflow:hidden; width:450px; height:px\"></iframe>";
                               html += @"</div>
                                    </div>
                                </div>";
                               
                            html += @"<div class='chiasewaitem'>
                            <div class='book-text'>Chia sẻ: </div>
                            <div class='detail-bookmark'>";
                              html +="<div class='dell'>";
                                html += "<a href=\"http://www.facebook.com/share.php?u=<url>\" onclick=\"return fbs_click();\" target='_blank'>";
                                html += " <img src=\"images/facebook-32x32.png\" alt='' />";
                                html += "</a>";
                              html +="</div>";
                              html +="<div class='dell'>";
                              html += "<a onclick=\"LoadOpenForm('http://twitter.com/home?status=2&url=');\">";
                              html += "   <img alt='' src=\"images/twitter-32x32.png\" />";
                                html += "</a>";
                              html +="</div>";
                              html +="<div class='dell'>";
                              html += "<a onclick=\"LoadOpenForm('http://www.google.com/bookmarks/mark?op=edit&output=popup&bkmk=');\">";
                              html += "<img alt='' src=\"images/google-32x32.png\" />";
                                html +="</a>";
                              html += "</div>";
                              html +="<div class='dell'>";
                                html += "<a onclick=\"javascript:window.open('http://bookmarks.yahoo.com/myresults/bookmarklet?u=' + window.location,'_blank');\">";
                                html += "<img alt='' src=\"images/yahoo-32x32.png\" />";
                                html += "</a>";
                              html += "</div>";
                              html += @"</div>
                                        </div>
                                </div>";
                              ltrTienIch.Text = html;
    }
    /// <summary>
    /// Hiển thị kiểu giá
    /// </summary>
    /// <param name="Price"></param>
    /// <param name="IsMapPrice"></param>
    /// <param name="Discount"></param>
    /// <returns></returns>
    private string Price(object Price, object IsMapPrice, object Discount, object ImageStatusID)
    {
        string html = "";
        //Nếu có discount và Không phải là MapPirce
        if (Discount != DBNull.Value && (int)Discount > 0 && (bool)IsMapPrice == false)
        {
            if (Price != DBNull.Value)
            {
                decimal price = Convert.ToDecimal(Price);
                decimal truePrice = price - (price * (int)Discount / 100);
                string[] arrPrice = truePrice.ToString("C").Split('.');
                html += string.Format("<div class=\"discount-price-d\"> <span class=\"new-price\">{0}</span> <br/><span class=\"old-price\">{1}<sup>.{2}</sup></span></div>",
                    price.ToString("C"), arrPrice[0], arrPrice[1]);
            }
        }
        else if ((bool)IsMapPrice == true)
        {
            if (Price != DBNull.Value)
            {
                decimal price = Convert.ToDecimal(Price);
                string[] arrPrice = price.ToString("C").Split('.');
                html += string.Format("<div class=\"map-price-d\">Map price <br/>{0}<sup>.{1}</sup></div>", arrPrice[0], arrPrice[1]);
            }
        }
        else if (Discount == DBNull.Value || (int)Discount == 0)
        {
            if (Price != DBNull.Value)
            {
                //Gía gốc
                decimal price = Convert.ToDecimal(Price);
                string[] arrPrice = price.ToString("C").Split('.');
                if ((byte)ImageStatusID == 3)
                {
                    //Tiền đặt cọc
                    decimal priceDeposit = Convert.ToDecimal(Price)/10;
                    string[] arrPriceDeposit = priceDeposit.ToString("C").Split('.');
                    html += string.Format("<div class=\"price-d\"><span>{0}<sup>.{1}</sup></span><br/>Deposit: <label>{2}<sup>.{3}</sup></label></div>", arrPrice[0], arrPrice[1],
                       arrPriceDeposit[0], arrPriceDeposit[1]);
                }
                else
                    html += string.Format("<div class=\"price-d\"><span>{0}<sup>.{1}</sup></span></div>", arrPrice[0], arrPrice[1]);
            }
        }
        
        return html;
    }
    private string ImageStock(object Quality, object ImageStatusID, object EstimateArrival)
    {
        string html = "";
        string strImage = "";
        if ((byte)ImageStatusID == 3)
        {
            if(EstimateArrival != DBNull.Value)
                html += string.Format("Estimate Arrival: <font color='red'>{0}</font>", EstimateArrival);
        }
        else
        {
            if (Quality != DBNull.Value)
            {
                if ((int)Quality > 0)
                    strImage = "bt_instock.jpg";
                else
                    strImage = "bt_soldout.jpg";
                html += string.Format(@"<img alt='' src='{0}/{1}' width='82' height='16'  /></a>",
                                            Config.Images, strImage);
            }
        }
        return html;
    }
    //Load image product
    protected string ImageProduct(object ImgPath, string TypeImage)
    {
        string strImage = "";
        if (ImgPath != DBNull.Value)
        {
            if (TypeImage !="small")
                strImage += string.Format("<img onclick=\"REDIPS.dialog.show(620, 385, '{0}/{1}')\" alt='{1}' style='cursor:pointer;' src='{0}/{1}' width='605' height='370'  /></a>",
                                            Config.IamgeProduct, ImgPath);
            else
                strImage += string.Format(@"<img alt='{1}' src='{0}/{1}' width='78'  /></a>",
                                           Config.IamgeProduct, ImgPath);
        }
        return strImage;
    }
    public void BindData()
    {
        DataSet dsProduct = null;
        try
        {
            int ProductID = string.IsNullOrEmpty(Request["pid"]) == null ? 0 : int.Parse(Request["pid"]);
            dsProduct = _Products.GetProductByID(ProductID);
            if (dsProduct != null)
            {
                //Thông tin sản phẩm
                #region "Thông tin sản phẩm"
                DataTable dtProduct= dsProduct.Tables[0];
                if (dtProduct != null)
                {
                    string NameProduct = dtProduct.Rows[0]["Name"] + "";
                    Page.Title = string.Format("Erchobbies | {0}", NameProduct);
                    lblHeader.Text = NameProduct;
                    lblCode.Text = dtProduct.Rows[0]["Code"] + "";
                    lblPrice.Text = Price(dtProduct.Rows[0]["Price"], dtProduct.Rows[0]["IsMapPrice"], dtProduct.Rows[0]["Discount"], (byte)dtProduct.Rows[0]["StatusProductID"]);
                    radRating.Value = Convert.ToDecimal(dtProduct.Rows[0]["Rating"]);
                    lblReview.Text = string.Format("&nbsp; {0} Reviews", dtProduct.Rows[0]["ReviewRating"] + "" == "" ? "0" : dtProduct.Rows[0]["ReviewRating"] + "");
                    //Ẩn hiện button
                    if (dtProduct.Rows[0]["StatusProductID"] != DBNull.Value && (byte)dtProduct.Rows[0]["StatusProductID"] == 3)
                    {
                        btnAddToCart.Visible = false;
                        btnReorder.Visible = true;
                    }
                    else
                    {
                        btnAddToCart.Visible = true;
                        btnReorder.Visible = false;
                    }
                    //Hiển thị ngày sản phẩm đến hoặc ảnh tồn kho
                    lblImageStock.Text = ImageStock(dtProduct.Rows[0]["Quality"], dtProduct.Rows[0]["StatusProductID"], dtProduct.Rows[0]["EstimateArrival"]);
                #endregion
                #region "Thông tin ảnh"
                    DataTable dtImage = dsProduct.Tables[1];
                    if (dtImage != null && dtImage.Rows.Count > 0)
                    {
                        //Large Image
                        rptImages.DataSource = dtImage;
                        rptImages.DataBind();
                        //Hiden Image
                        rptHiden.DataSource = dtImage;
                        rptHiden.DataBind();
                        //Small Image
                        rptSmallImage.DataSource = dtImage;
                        rptSmallImage.DataBind();
                    }
                    else
                    {
                        pnHiden.Visible = true;
                        pnSmallImage.Visible = true;
                        pnLargeNoImage.Visible = true;
                    }
                #endregion
                }
                //Bind Image
                //rptImagesPro.DataSource = dtProduct;
                //rptImagesPro.DataBind();
                //rptSmallImages.DataSource = dtProduct;
                //rptSmallImages.DataBind();
                //lblSummary.Text = dtProducts.Rows[0]["Summary"] + "";
            }
          
            //dtNewDetail = _dsProductsDetail.Tables[0];
            //rptLastProducts.DataSource = _dsProductsDetail.Tables[1];
            //rptLastProducts.DataBind();
        }
        catch (Exception ex)
        {
            TrackingError.AddTrackingError("Author: sanghv - Funtion: BindData - Page:  Products_detail", ex.Message);
        }

    }
    protected void btnAddToCart_Click(object sender, ImageClickEventArgs e)
    {
        if (!string.IsNullOrEmpty(txtQuantity.Text))
        {
            string Name = "", Code = "", ImageURL = "", EstimateArrival = "", CategoryID = "";
            int Discount = 0, intQuantity = 0;
            bool IsMapPrice = false;
            decimal Price = 0M;
            int ProductID = int.Parse(Request.QueryString["pid"]+ "");
            //Khởi tạo session Cart
            DataTable dtCart = new DataTable();
            if (Session[Config.SessionCart] == null)
            {
                dtCart.Columns.Add("ProductID", typeof(int));
                dtCart.Columns.Add("Name", typeof(string));
                dtCart.Columns.Add("Code", typeof(string));
                dtCart.Columns.Add("Price", typeof(decimal));
                dtCart.Columns.Add("ImageURL", typeof(string));
                dtCart.Columns.Add("IsMapPrice", typeof(bool));
                dtCart.Columns.Add("Quantity", typeof(int));
                dtCart.Columns.Add("EstimateArrival", typeof(string));
                dtCart.Columns.Add("CategoryID", typeof(string));
            }
            else
            {
                dtCart = (DataTable)Session[Config.SessionCart];
            }
            //Lấy dữ liệu của product
            DataTable dtProduct = _Products.GetProductByIDCart(ProductID);
            if (dtProduct != null && dtProduct.Rows.Count > 0)
            {
                //Gán biến
                Name = dtProduct.Rows[0]["Name"] + "";
                Code = dtProduct.Rows[0]["Code"] + "";
                Price = (decimal)dtProduct.Rows[0]["Price"];
                intQuantity = int.Parse(txtQuantity.Text);
                decimal truePrice = (Price - (Price * (int)Discount / 100)) * intQuantity;
                ImageURL = dtProduct.Rows[0]["ImageURL"] + "";
                IsMapPrice = (bool)dtProduct.Rows[0]["IsMapPrice"];
                EstimateArrival = dtProduct.Rows[0]["EstimateArrival"] + "";
                CategoryID = dtProduct.Rows[0]["CategoryID"] + "";
                foreach (DataRow row in dtCart.Rows)
                {
                    if (ProductID == (int)row["ProductID"])
                    {
                        truePrice += (decimal)row["Price"];
                        intQuantity += (int)row["Quantity"];
                        row.Delete();
                        break;
                    }
                }
                //Thêm sản phẩm vào Cart
                dtCart.Rows.Add(ProductID, Name, Code, truePrice, ImageURL, IsMapPrice, intQuantity, EstimateArrival);
                Session[Config.SessionCart] = dtCart;
            }
            Response.Redirect("shopping-cart.aspx", true);
        }
    }
}